package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import entity.Area;

@WebServlet("/area")
public class AreaServlet extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("utf-8");

		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tb108", "root", "root");
			Statement sta = conn.createStatement();
			ResultSet rs = sta.executeQuery("select * from area");
			List<Area> areas = new ArrayList<Area>();
			while (rs.next()) {
				Area a = new Area();
				a.setId(rs.getInt("id"));
				a.setName(rs.getString("name"));
				areas.add(a);
			}
			rs.close();
			sta.close();
			conn.close();

			Area a = areas.get(0);
			String aj = JSON.toJSONString(a);
			System.out.println(aj);

			String areasJson = JSONArray.toJSONString(areas);
			System.out.println(areasJson);
			PrintWriter pw = response.getWriter();
			pw.write(areasJson);
			pw.close();

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
